package com.southminority.ethnic.controller.admin.student;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.controller.student.vo.AwardPageVo;
import com.southminority.ethnic.pojo.StudentAward;
import com.southminority.ethnic.service.student.StudentAwardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生获奖管理后台控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "学生获奖管理API", description = "【后台】学生获奖模块的增删改查接口")
@RestController
@RequestMapping("/admin/student/award")
@CrossOrigin
public class StudentAwardAdminController {

    private final StudentAwardService awardService;

    public StudentAwardAdminController(StudentAwardService awardService) {
        this.awardService = awardService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询学生获奖", description = "后台管理使用的学生获奖列表接口，支持关键词搜索、状态筛选和分页。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<Page<AwardPageVo>> getAwardPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "搜索关键词（标题、学生姓名、获奖等级）", example = "一等奖") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态筛选（0-草稿，1-已发布，2-已下架，不传表示全部）", example = "1") @RequestParam(required = false) Integer status) {
        try {
            Page<AwardPageVo> pageResult = awardService.getAwardPage(pageNum, pageSize, keyword, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询学生获奖失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取学生获奖详情", description = "根据ID查询学生获奖的完整信息。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<StudentAward> getAwardDetail(
            @Parameter(description = "获奖记录ID", example = "1", required = true) @PathVariable Long id) {
        try {
            StudentAward award = awardService.getById(id);
            if (award == null) {
                return R.fail("获奖记录不存在");
            }
            return R.ok(award);
        } catch (Exception e) {
            log.error("获取学生获奖详情失败", e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建学生获奖记录", description = "创建新的学生获奖记录。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "创建失败")
    })
    public R<StudentAward> createAward(
            @Parameter(description = "学生获奖数据", required = true)
            @RequestBody @Valid StudentAward award) {
        try {
            // 设置默认值
            if (award.getViews() == null) {
                award.setViews(0);
            }
            if (award.getStatus() == null) {
                award.setStatus(1); // 默认已发布
            }
            
            boolean success = awardService.save(award);
            if (success) {
                log.info("创建学生获奖记录成功: ID={}, 标题={}", award.getId(), award.getTitle());
                return R.ok(award);
            } else {
                return R.fail("创建失败");
            }
        } catch (Exception e) {
            log.error("创建学生获奖记录失败", e);
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "更新学生获奖记录", description = "根据ID更新学生获奖信息。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<StudentAward> updateAward(
            @Parameter(description = "要更新的获奖记录ID", example = "1", required = true) @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "包含更新字段的获奖记录JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = StudentAward.class)))
            @org.springframework.web.bind.annotation.RequestBody StudentAward award) {
        try {
            StudentAward existingAward = awardService.getById(id);
            if (existingAward == null) {
                return R.fail("获奖记录不存在");
            }
            
            award.setId(id);
            boolean success = awardService.updateById(award);
            if (success) {
                log.info("更新学生获奖记录成功: ID={}, 标题={}", id, award.getTitle());
                return R.ok(awardService.getById(id));
            } else {
                return R.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新学生获奖记录失败", e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除学生获奖记录", description = "根据ID删除学生获奖记录（物理删除）。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteAward(
            @Parameter(description = "要删除的获奖记录ID", example = "1", required = true) @PathVariable Long id) {
        try {
            StudentAward existingAward = awardService.getById(id);
            if (existingAward == null) {
                return R.fail("获奖记录不存在");
            }
            
            boolean success = awardService.removeById(id);
            if (success) {
                log.info("删除学生获奖记录成功: ID={}", id);
                return R.ok(true);
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除学生获奖记录失败", e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除学生获奖记录", description = "传入ID列表，批量删除学生获奖记录。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "ID列表为空"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> batchDeleteAward(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "包含多个获奖记录ID的数组", required = true,
                    content = @Content(schema = @Schema(type = "array", implementation = Long.class)))
            @org.springframework.web.bind.annotation.RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return R.fail("ID列表不能为空");
            }
            
            boolean success = awardService.removeByIds(ids);
            if (success) {
                log.info("批量删除学生获奖记录成功: IDs={}", ids);
                return R.ok(true);
            } else {
                return R.fail("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除学生获奖记录失败", e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新学生获奖记录状态", description = "更新获奖记录的发布状态。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateAwardStatus(
            @Parameter(description = "获奖记录ID", example = "1", required = true) @PathVariable Long id,
            @Parameter(description = "新的状态值", example = "1", required = true,
                    schema = @Schema(description = "0-草稿, 1-已发布, 2-已下架", type = "integer"))
            @RequestParam Integer status) {
        try {
            StudentAward existingAward = awardService.getById(id);
            if (existingAward == null) {
                return R.fail("获奖记录不存在");
            }
            
            existingAward.setStatus(status);
            boolean success = awardService.updateById(existingAward);
            if (success) {
                log.info("更新学生获奖记录状态成功: ID={}, Status={}", id, status);
                return R.ok(true);
            } else {
                return R.fail("状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新学生获奖记录状态失败", e);
            return R.fail("状态更新失败: " + e.getMessage());
        }
    }

    @GetMapping("/test")
    @Operation(summary = "测试接口连通性", description = "一个简单的GET请求，用于检查服务是否正常运行。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "服务正常")
    })
    public R<String> test() {
        return R.ok("学生获奖管理后台服务正常");
    }
}
